<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>LocalStorage window.onstorage </title>
  <style>
    :root {
      font-size: 14px;
      
    }
    #List {
      font-size: 1.2rem;
    }
    #List li {
      margin-bottom: 10px;
    }
    #List input, #List button {
      padding: 2px 10px;
      height: 30px;
      box-sizing: border-box;
      outline: none;
      font-size: inherit;
    }
  </style>
</head>
<body>
  <button onclick="add()">添加</button>
  <ul id="List">
    
  </ul>
  <script>
    const domUl = document.getElementById('List');

    const storageList = Object.entries(localStorage);
    for(let value of storageList) {
      const li = createFrame(value[0], value[1]);
      domUl.appendChild(li)
    }


    function createFrame(key = '', value = '') {
      const frame = document.createElement('li');
      frame.data = key;
      frame.innerHTML = `<label for="">key：</label><input class="key" type="text" value="${key}" autocomplete="off">
        <span style="margin: 0 10px;">|</span>
        <label for="">value：</label><input class="value" type="text" value="${value}" autocomplete="off">
        <button onclick="update(this)">修改</button> <button onclick="remove(this)">删除</button>`
      return frame;
    }
    function update(self) {
      const parentLi =  self.parentNode;
      let key = parentLi.data;
      const value = parentLi.querySelector('.value').value;
      if (!key) {
        key = parentLi.querySelector('.key').value
        parentLi.data = key

      }
      if (value) {
        localStorage.setItem(key, value)
      }
    }
    function remove(self) {
      const parentLi =  self.parentNode;
      const key = parentLi.data;
      localStorage.removeItem(key);
      domUl.removeChild(parentLi)
    }
    function add() {
      const li = createFrame();
      domUl.insertBefore(li, domUl.childNodes[0])
    }

    // 事件是在另一个标签页上触发，当前标签页上不显示
    window.onstorage = function(event) {  // storageEvent
      console.log(event)
      //  storageEvent 的部分属性
      /**
       * e.target: Window,  事件目标
       * e.type: 'storage', 事件类型
       * e.key, 发生修改的键名
       * e.oldValue,  正在修改键的旧值
       * e.newValue,  正在修改键的新值
       * e.url, 修改键值时所在的url
       * e.storageArea: Storage { key, value, t, length } 受影响的存储对象
       * 
      */
      
    };
  </script>
</body>
</html>